<template>
  <div>
    <el-form ref="deptForm" label-width="120px">
      <el-form-item label="部门名称">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getSimpleEmployees } from '@/api/employees.js'
import { addDepartment, getDepartmentById, updateDepartmentById } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employees: [] // 部门负责人列表

    }
  },
  created() {
    this.loadEmployees()
    this.loadDepartmentDetail()
  },
  methods: {
    // 发请求添加 需要传入 form
    async hSubmit() {
      // 兜底校验
      // 根据当前状态去判断是编辑还是新增 发送不同的请求
      try {
        let res = null
        if (this.isEdit) {
          res = await updateDepartmentById(this.form)
        } else {
          this.form.pid = this.id
          res = await addDepartment(this.form)
        }

        // console.log(res)
        this.$message.success(res.message)
        this.$emit('success')
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    hCancel() {
      this.$emit('close')
    },
    async loadEmployees() {
      // 获取部门负责人列表 发送请求
      try {
        const res = await getSimpleEmployees()
        // console.log(res)
        this.employees = res.data
      } catch (e) {
        console.log(e)
      }
    },
    async loadDepartmentDetail() {
      if (!this.isEdit) return
      const res = await getDepartmentById(this.id)
      this.form = res.data // 数据回填
    }
  }

}
</script>

